package mail.util;

import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Store;

/**
 * Class that is used for recieving mails
 * 
 * @author Jonas Lindmark
 */
public class Reciever {
    private String iID,iPass,iHost;
    private Properties iProperties = null;
    public void setLoginID(String id)
    {
        iID = id;
    }
    public void setLoginPassword(String pass)
    {
        iPass = pass;
    }
    public void setHost(String host)
    {
        iHost = host;
    }
    public List<Mail> checkNewMail() throws Exception
    {
        if (iID == null || iPass == null || iHost == null)
        {
            throw new Exception("Properties not set in a satisfiable way");
        }

        
        try
        {
            Session session = Session.getDefaultInstance(iProperties, null);
            Store store = session.getStore("pop3");
            store.connect(iHost,iID,iPass);

            Folder inbox = store.getFolder("Inbox");
            //Folder inbox = store.getDefaultFolder();
            inbox.open(Folder.READ_ONLY);
            final Message messages[] = inbox.getMessages();
            try
            {
                final List<Mail> res = getAllMessages(messages);
                inbox.close(true);
                store.close();
                return res;
            }
            catch (Exception ex)
            {
                System.err.println("Failed to close up after reading mail.");
                ex.printStackTrace();
            }
        }
        catch (MessagingException e)
        {
            e.printStackTrace();
            System.exit(2);
        }
        return null;
    }
    /**
     * Creates a new default instance which uses pop3
     */
    public Reciever()
    {
        iProperties = System.getProperties();
        iProperties.setProperty("mail.store.protocol", "pop3");
    }

    /**
     * used to convert Messages to mails
     * 
     * @param msgs
     * @return
     * @throws Exception 
     */
    public List<Mail> getAllMessages(Message[] msgs) throws Exception
    {
        ArrayList<Mail> mails = new ArrayList();
        for (int i = 0; i < msgs.length; i++)
        {
            mails.add(MessagePrinter.extractMail(msgs[i]));
        }
        return mails;
    }
    
}

